package cn.maxmc.murderaddons.listener

import cn.maxmc.murderaddons.command.MainCommand
import cn.maxmc.murderaddons.machine.BaseMachine
import cn.maxmc.murderaddons.machine.machines.ScannerMachine
import cn.maxmc.murderaddons.task.ArenaTaskManager
import io.izzel.taboolib.module.inject.TListener
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.event.player.PlayerToggleSneakEvent
import plugily.projects.murdermystery.arena.ArenaRegistry
import kotlin.math.roundToInt

@TListener
class PlayerListener: Listener {

    @EventHandler
    fun onQuit(e: PlayerQuitEvent) {
        MainCommand.playerMap.remove(e.player)
    }

    @EventHandler
    fun onToggleSneak(e: PlayerToggleSneakEvent) {
        if(!e.isSneaking) {
            return
        }

        val arena = ArenaRegistry.getArena(e.player) ?: return

        val task = ArenaTaskManager.tasksCache[arena]?:return

        val machines = ArrayList<BaseMachine>()

        val playerTask = task.task[e.player] ?: return
        playerTask.tasks.forEach { machine ->
            if (machine.mainLocation.distance(e.player.location) < 5) {
                machines.add(machine)
            }
        }

        if(machines.isEmpty()) {
            return
        }

        machines.sortWith { m1,m2 ->
            return@sortWith ((m1.mainLocation.distance(e.player.location) - m2.mainLocation.distance(e.player.location))*10).roundToInt()
        }

        val machine = machines[0]

        if(!machine.isFinish(e.player)){
            machine.requestTask(e.player,e.player.location)
        }
    }
}